package net.suntec.mrs.message;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileMessageContentHandler implements MessageContentHandler {

	/** Logger */
	private static final Logger logger = LoggerFactory.getLogger( FileMessageContentHandler.class );

	private static final String UPLOAD_FILE_PATH = "D:\\upload_files";

	/** 文件channel */
	private FileChannel fileChannel;

	public FileMessageContentHandler() throws IOException {

		// 随机生成一个文件名
		final String fileName = UUID.randomUUID().toString();

		// 生成一个零时文件
		String filePath = UPLOAD_FILE_PATH + "\\" + fileName;
		RandomAccessFile randomAccessFile = new RandomAccessFile( filePath, "rw" );
		fileChannel = randomAccessFile.getChannel();

		if ( logger.isDebugEnabled() )
			logger.debug( "Create a template file. path: {}", filePath );
	}

	@Override
	public void write( ByteBuffer msg_content ) throws IOException {
		if ( fileChannel != null )
			fileChannel.write( msg_content );
	}

	@Override
	public void read( ByteBuffer msg_content, String msgId ) {

	}

	@Override
	public void complete() {
		if ( fileChannel != null )
			try {
				fileChannel.close();
			}
			catch ( IOException e ) {
				// ignore
			}
	}
}
